﻿using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Syspetro.Deploy.Managers;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Security.Claims;
using System.Security.Cryptography;

namespace Syspetro.Deploy.Jwt
{
    /// <summary>
    /// 公钥和私钥模式授权
    /// </summary>
    public class JwtRSService : IJwtService
    {
        #region Option注入
        readonly ITokenCache Cache;
        private readonly JwtTokenOptions _JWTTokenOptions;
        readonly IAuthorizationManager _authorization;
        public JwtRSService(IOptionsMonitor<JwtTokenOptions> jwtTokenOptions, ITokenCache tokenCache, IAuthorizationManager authorization)
        {
            this._JWTTokenOptions = jwtTokenOptions.CurrentValue;
            Cache = tokenCache;
            _authorization = authorization;
            Cache.ExpireTimeSpan = new TimeSpan(0, _JWTTokenOptions.ExpiredTime, 0);
        }
        #endregion
        public (Guid, string) GetToken(IUserAuth userModel)
        {
            if (string.IsNullOrEmpty(userModel.RoleName))
            {
                userModel.RoleName = "-";
                userModel.IsAdmin = false;
            }
            var claims = new[]
            {
                   new Claim(ClaimTypes.Name, userModel.UserName),
                   new Claim(ClaimTypes.Role, userModel.RoleName),
                   new Claim("Account", userModel.Account),
                   new Claim("Level", userModel.Level.ToString()),
                   new Claim("Phone", userModel.Phone ?? ""),
                   new Claim("Emil", userModel.Emil ?? ""),
                   new Claim("IsAdmin", userModel.IsAdmin.ToString()),
                   new Claim("UserId", userModel.UserId.ToString())
            };
            var token = CreateToken(claims);
            Serilog.Log.Information("用户登录：" + userModel.UserName);
            if (_JWTTokenOptions.ExpiredRefresh > 0)
            {
                var id = Guid.NewGuid();
                if (_JWTTokenOptions.ExpiredRefresh == 0) _JWTTokenOptions.ExpiredRefresh = 1440;
                Cache.Add(userModel.UserId, id, token);
                return (id, token);
            }
            else
            {
                return (Guid.Empty, token);
            }
        }
        public string RefreshToken(Guid tokenId)
        {
            var token = Cache.GetByToken(tokenId);
            if (token != null)
            {
                string path = Path.Combine(Directory.GetCurrentDirectory(), "tokenkey.public.json");
                var clims = JWTEncryption.GetPrincipalFromAccessTokenRs(token, path);
                if (clims != null)
                {
                    var newtoken = CreateToken(clims.Claims);
                    Cache.Refresh(tokenId, newtoken);
                    return newtoken;
                }
            }
            return null;
        }

        private string CreateToken(IEnumerable<Claim> claims)
        {
            var time = _JWTTokenOptions.ExpiredTime;
            if (_JWTTokenOptions.ExpiredRefresh > 0)
                time = _JWTTokenOptions.ExpiredRefresh;
            if (time <= 0)
                time = 5;

            string keyDir = Directory.GetCurrentDirectory();
            if (RSATokenHelper.TryGetKeyParameters(keyDir, true, out RSAParameters keyParams) == false)
            {
                keyParams = RSATokenHelper.GenerateAndSaveKey(keyDir);
            }
            var credentials = new SigningCredentials(new RsaSecurityKey(keyParams), SecurityAlgorithms.RsaSha256Signature);

            var token = new JwtSecurityToken(
               issuer: this._JWTTokenOptions.ValidIssuer,
               audience: this._JWTTokenOptions.ValidAudience,
               claims: claims,
               expires: DateTime.Now.AddMinutes(time),//5分钟有效期
               notBefore: DateTime.Now,//开始生效的时间(意味着在这个时间之前验证JWT是会失败的)
               signingCredentials: credentials);
            var handler = new JwtSecurityTokenHandler();
            return handler.WriteToken(token);
        }

        public void RemoveToken(Guid tokenid)
        {
            var userid = _authorization.GetUserId;
            Cache.RemoveByUser(userid, tokenid);
        }
    }
}
